package chan.project.smartlawlawyer.controller.inner;
import chan.project.smartlawcommon.common.BaseResponse;
import chan.project.smartlawcommon.common.ErrorCode;
import chan.project.smartlawcommon.common.ResultUtils;
import chan.project.smartlawcommon.exception.BusinessException;
import chan.project.smartlawcommon.exception.ThrowUtils;
import chan.project.smartlawlawyer.service.LawyerInfoService;
import chan.project.smartlawmodel.entity.LawyerInfo;

import chan.project.smartlawservice.lawyerService.LawyerInfoFeignClient;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/lawyer/inner")
public class LawyerInfoControllerInner implements LawyerInfoFeignClient {

    @Resource
    private LawyerInfoService lawyerInfoService;

    @Override
    @PostMapping("register")
    public boolean lawyerRegister(@RequestBody LawyerInfo info) {
        if(ObjectUtil.isEmpty(info)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LambdaQueryWrapper<LawyerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerInfo::getUserId,info.getUserId());
        LawyerInfo one = lawyerInfoService.getOne(queryWrapper);
        if(ObjectUtil.isNotEmpty(one)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"该用户已有账号");
        }
        boolean save = lawyerInfoService.save(info);
        ThrowUtils.throwIf(!save,ErrorCode.OPERATION_ERROR);
        return save;
    }

    @Override
    @GetMapping("/getLawyer")
    public LawyerInfo getLawyerInfo(@RequestParam("userId")Long userId) {
        LambdaQueryWrapper<LawyerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerInfo::getUserId,userId);
        LawyerInfo one = lawyerInfoService.getOne(queryWrapper);
        return one;
    }

    @Override
    @GetMapping("/getLawyerByList")
    public List<LawyerInfo> getLawyerByList(List<String> userIdList) {
        if (userIdList == null || userIdList.isEmpty()) {
            return Collections.emptyList();
        }
        // 转换为Long类型的ID列表
        List<Long> longUserIdList = userIdList.stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        // 使用in查询，一次性查询所有数据，避免N+1问题
        LambdaQueryWrapper<LawyerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(LawyerInfo::getUserId, longUserIdList);
        return lawyerInfoService.list(queryWrapper);
    }
}
